package my.diplom.web.controllers;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.validation.BindException;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.apache.log4j.Logger;
import my.diplom.dao.service.*;
import my.diplom.entity.*;
import my.diplom.util.OrderUtil;
import my.diplom.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;

/**
 * Created by IntelliJ IDEA.
 * User: GGobozov
 * Date: 10.08.2009
 * Time: 13:32:41
 * To change this template use File | Settings | File Templates.
 */
public class OrderController extends SimpleFormController {

    private static final Logger log = Logger.getLogger(OrderController.class);
    private OrderService orderService;
    private StatusService statusService;
    private ApplicationService applicationService;
    private ProjectService projectService;
    private UserService userService;
    private CategoryService categoryService;
    private PriorityService priorityService;
    private HostService hostService;
    private ResourceService resourceService;

    public OrderController() {
        setCommandClass(Order.class);
        setCommandName("newOrder");
        setSessionForm(false);
        setBindOnNewForm(false);
    }


    public void setResourceService(ResourceService resourceService) {
        this.resourceService = resourceService;
    }

    public void setHostService(HostService hostService) {
        this.hostService = hostService;
    }

    public void setPriorityService(PriorityService priorityService) {
        this.priorityService = priorityService;
    }

    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    public void setStatusService(StatusService statusService) {
        this.statusService = statusService;
    }

    public void setProjectService(ProjectService projectService) {
        this.projectService = projectService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    public void setApplicationService(ApplicationService applicationService) {
        this.applicationService = applicationService;
    }

    @Override
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        if (request.getParameter("orderId") != null && request.getParameter("action").equals("edit")) {
            Order order = orderService.getById(Long.parseLong(request.getParameter("orderId")));
            request.setAttribute("editedOrder", order);
            return order;
        } else {
            Order order = new Order();
            return order;
        }
    }


    @Override
    protected Map referenceData(HttpServletRequest request) throws Exception {
        HashMap<String, Object> model = new HashMap<String, Object>();

        if (UserUtil.isAdmin()) {
            List<Project> projects = projectService.getAll();
            List<Order> orders = orderService.getAll();
            List<Status> statuces = statusService.getOrderStatuces();
            List<Host> hosts = hostService.getAll();
            List<Resource> resources = resourceService.getAll();
            OrderUtil.setAppropriateHosts(orders, hosts);
            model.put("resources", resources);
            model.put("statuces", statuces);
            model.put("projects", projects);
            model.put("orders", orders);
        } else {
            List<Project> projects = projectService.getByLogin(UserUtil.getRemoteUser());
            List<Order> orders = orderService.getByLogin(UserUtil.getRemoteUser());
            model.put("projects", projects);
            model.put("orders", orders);
        }

        List<Category> categories = categoryService.getAllActive();
        List<Priority> priorities = priorityService.getAll();
        List<Float> cpuList = OrderUtil.getCpuList(getServletContext());
        List<Float> hddList = OrderUtil.getHddList(getServletContext());
        List<Float> ramList = OrderUtil.getRamList(getServletContext());

        model.put("categories", categories);
        model.put("priorities", priorities);
        model.put("cpuList", cpuList);
        model.put("hddList", hddList);
        model.put("ramList", ramList);
        return model;
    }


    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
        Order order = (Order) command;
        if (UserUtil.isAdmin()) {
            orderService.update(order);
        } else {
            order.setUser(userService.getByLogin(UserUtil.getRemoteUser()));
            order.setStatus(statusService.getByName("submitted"));
            orderService.create(order);
        }
        return new ModelAndView(new RedirectView("createOrder.htm"));
    }

    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

        binder.registerCustomEditor(Project.class, "project", new PropertyEditorSupport() {

            public void setAsText(String text) {
                if (text instanceof String) {
                    Long projectId = Long.parseLong(text);
                    Project project = projectService.getById(projectId);
                    setValue(project);

                }
            }

            public String getAsText() {
                Object value = getValue();
                if (value != null) {
                    Project project = (Project) value;
                    return project.getProjectName();
                }
                return null;
            }


        });

        binder.registerCustomEditor(Set.class, "applications", new CustomCollectionEditor(Set.class) {


            protected Object convertElement(Object element) {
                if (element != null) {
                    Long applicationId = Long.parseLong(element.toString());
                    Application application = applicationService.getById(applicationId);
                    return application;

                }
                return null;
            }

        });

        binder.registerCustomEditor(Date.class, "startDate", new CustomDateEditor(dateFormat, false) {

        });

        binder.registerCustomEditor(Date.class, "finishDate", new CustomDateEditor(dateFormat, false) {

        });

        binder.registerCustomEditor(Status.class, "status", new PropertyEditorSupport() {

            public void setAsText(String text) {
                if (text instanceof String) {
                    if (text != null && text.trim().length() > 0) {
                        Long statusId = Long.parseLong(text);
                        Status status = statusService.getById(statusId);
                        setValue(status);
                    }

                }
            }

            public String getAsText() {
                Object value = getValue();
                if (value != null) {
                    Status status = (Status) value;
                    return status.getStatusName();
                }
                return null;
            }


        });

        binder.registerCustomEditor(Priority.class, "priority", new PropertyEditorSupport() {

            public void setAsText(String text) {
                if (text instanceof String) {
                    if (text != null && text.trim().length() > 0) {
                        Long priorityId = Long.parseLong(text);
                        Priority priority = priorityService.getById(priorityId);
                        setValue(priority);
                    }

                }
            }

            public String getAsText() {
                Object value = getValue();
                if (value != null) {
                    Priority priority = (Priority) value;
                    return priority.getPriorityName();
                }
                return null;
            }


        });


         binder.registerCustomEditor(Resource.class, "resource", new PropertyEditorSupport() {

            public void setAsText(String text) {
                if (text instanceof String) {
                    if (text != null && text.trim().length() > 0) {

                        Long resourceId = Long.parseLong(text);
                        Resource resource = resourceService.getById(resourceId);
                        setValue(resource);
                    }

                }
            }

            public String getAsText() {
                Object value = getValue();
                if (value != null) {
                    Resource resource = (Resource) value;
                    return resource.getHostName();
                }
                return null;
            }


        });

    }


}
